package cn.zyy.hotel.controller;

import cn.zyy.hotel.entity.Orders;
import cn.zyy.hotel.entity.User;
import cn.zyy.hotel.service.OrdersService;
import cn.zyy.hotel.utils.Result;
import cn.zyy.hotel.utils.SystemConstant;
import cn.zyy.hotel.utils.UUIDUtils;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/orders")
public class OrdersController {

    @Resource
    private OrdersService ordersService;

    private static Orders orders;

    //appid
    private final String APP_ID = "2021000119687642";
    //应用私钥
    private final String APP_PRIVATE_KEY = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCqhLlWg8Je3zzMrCwEF/UCTFBdDsLU9kuRSSrHa6Fd5hIl9CV2moTwa4PmVuSXvCIrK4mFCyuivoGLPMv6Jph4dCuFcIapdbisAhrTc0sm+6uVFd1ty5Vz7gg1x3uTj9EHT/LCmmN78KQPi+J0NfeefSs3oGG5DNsvzwfBXAndWgOKx7GqG0fxR3OiwltMPY7gD2qpotACJ9FT9uP/ktMrDk4/9p19QmwWQyVOmrfQMhI3LtjbW5pbC+NhliEBYdYZ6Pd+eklgaUoFSnpgWWuYvGl6HG5bwPla4AV9K2eM73IL3SiF01v+y0ud/yiNRIkOI3ERyBBHvjOpRvPW3ZOtAgMBAAECggEAKOi8ulfUCwTNxmDMEpNY0ZtTcG/5KDSKvqlqHPvic++djQN89W5u1GtG8r0IDKszG15PmN6sMlg4JhqI6VPXIp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7Khj4CA6VT3zBjLFPdzrcMX3FMzv0vm5TLzlligD9uiJGV5K";
    private final String CHARSET = "UTF-8";
    // 支付宝公钥
    private final String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqoS5VoPCXt88zKwsBBf1AkxQXQ7C1PZLkUkqx2uhXeYSJfQldpqE8GuD5lbkl7wiKyuJhQsror6BizzL+iaYeHQrhXCGqXW4rAIa03NLJvurlRXdbcuVc+4INcd7k4/RB0/ywppje/CkD4vidDX3nn0rN6BhuQzbL88HwVwJ3VoDisexqhtH8UdzosJbTD2O4A9qqaLQAifRU/bj/5LTKw5OP/adfUJsFkMlTpq30DISNy7Y21uaWwvjYZYhAWHWGej3fnpJYGlKBUp6YFlrmLxpehxuW8D5WuAFfStnjO9yC90ohdNb/stLnf8ojUSJDiNxEcgQR74zqUbz1t2TrQIDAQAB";
    //这是沙箱接口路径,正式路径为https://openapi.alipay.com/gateway.do
    private final String GATEWAY_URL ="https://openapi.alipaydev.com/gateway.do";
    private final String FORMAT = "JSON";
    //签名方式
    private final String SIGN_TYPE = "RSA2";
    //支付宝异步通知路径,付款完毕后会异步调用本项目的方法,必须为公网地址
    private final String NOTIFY_URL =  "http://95z8kq.natappfree.cc/notify_url.jsp";
    //支付宝同步通知路径,也就是当付款完毕后跳转本项目的页面,可以不是公网地址
    private final String RETURN_URL = "http://localhost:8080/hotel/orders/returnUrl";



    @ResponseBody
    //@RequestMapping("/addOrders")
    public Object addOrders(Orders orders){
        Map<String, Object> map = new HashMap<String, Object>();
        //调用添加订单的方法
        if (ordersService.addOrders(orders) > 0){
            map.put(SystemConstant.SUCCESS,true);
            map.put(SystemConstant.MESSAGE,"房间预定成功");
        }else {
            map.put(SystemConstant.SUCCESS,false);
            map.put(SystemConstant.MESSAGE,"房间预定失败，请重试!");
        }
        return map;
    }

    //根据用户id查询订单
    @ResponseBody
    @RequestMapping("/list")
    public Object list(HttpSession session){
        User user = (User) session.getAttribute(SystemConstant.FRONT_LOGIN_USER);
        List<Orders> orders = ordersService.selectOrdersListByUserId(user.getId());
        return Result.builder().code(0).data(orders).build();
    }

    //添加订单
    @RequestMapping("/addOrders")
    public void payController(Orders orders, HttpServletResponse response) throws AlipayApiException {
        orders.setOrdersNo(UUIDUtils.randomUUID());
        OrdersController.orders = orders;
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL,APP_ID,APP_PRIVATE_KEY,FORMAT,CHARSET,ALIPAY_PUBLIC_KEY,SIGN_TYPE);
        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(RETURN_URL);
        alipayRequest.setNotifyUrl(NOTIFY_URL);
        //商户订单号
        String out_trade_no = orders.getOrdersNo();
        // 付款金额
        String total_amount = String.valueOf(orders.getReservePrice());
        // 订单名称
        String subject = String.valueOf(orders.getRoomTypeId());
        // 商品描述
        String body = "";
        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\"," + "\"total_amount\":\"" + total_amount
                + "\"," + "\"subject\":\"" + subject + "\"," + "\"body\":\"" + body + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //请求
        String form = "";
        try {
            form = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        response.setContentType("text/html;charset=" + CHARSET);
        try {
            response.getWriter().write(form);//直接将完整的表单html输出到页面
            response.getWriter().flush();
            response.getWriter().close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("returnUrl")
    public String returnUrlMethod(HttpServletRequest request, HttpSession session) throws AlipayApiException, UnsupportedEncodingException {
        // 获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        //验证签名（支付宝公钥）
        boolean signVerified = AlipaySignature.rsaCheckV1(params, ALIPAY_PUBLIC_KEY, CHARSET, SIGN_TYPE); // 调用SDK验证签名
        //验证签名通过
//        if(signVerified){
//
//        }else{
//
//        }
        ordersService.addOrders(orders);
        orders = null;
        return "redirect:/index.jsp";
    }


}
